<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title></title>
	<script src="./lib/vue-2.4.0.js"></script>
	<link rel="stylesheet" href="./lib/bootstrap-3.3.7.css">
</head>
<body>
<div id="app">
	<!-- 操作 -->
	<div class="panel panel-primary">
      <div class="panel-heading">
        <h3 class="panel-title">添加品牌</h3>
      </div>
      <div class="panel-body form-inline">
        <label>
          Id：<input type="text" class="form-control" v-model="id">
        </label>

        <label>
          Name：<input type="text" class="form-control" v-model="name">
        </label>

        <!-- 在Vue中，使用事件绑定机制，为元素指定处理函数的时候，如果加了小括号，就可以给函数传参了 -->
        <input type="button" value="添加" class="btn btn-primary" @click="add()">

        <label>
          搜索名称关键字：
          <input type="text" class="form-control" v-model="keywords">
        </label>
      </div>
    </div>
	<!-- 数据 -->
	<table class="table table-bordered table-hover table-striped">
		<thead>
			<tr>
				<th>编号</th>
				<th>名字</th>
				<th>时间</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="item in search(keywords)" :key="item.id">
				<td>{{ item.id }}</td>
				<td v-text="item.name"></td>
				<td>{{ item.ctime }}</td>
				<td><button @click.prevent="del(item.id)">删除</button></td>
			</tr>
		</tbody>
	</table>
</div>
<script>
var vm = new Vue({
	el: '#app',
	data: {
		id: '',
		name: '',
		keywords:'',
		list: [
			{ id: 1 , name:'奔驰1', ctime: new Date() },
			{ id: 2 , name:'奔驰2', ctime: new Date() },
			{ id: 3 , name:'奔驰3', ctime: new Date() },
		]
	},
	methods:{
		add(){ // 添加数据
			var coder = {
				id: this.id,
				name: this.name,
				ctime: new Date()
			};
			this.list.unshift(coder);
			this.id = this.name = '';
		},
		del(id){  // 删除数据
			// this.list.some(( item , i ) => {
			// 	if ( item.id == id ) {
			// 		this.list.splice(i,1);
			// 		return true;
			// 	}
			// })
			// 
			
			var index = this.list.findIndex( (item,i) =>{
				if ( item.id == id ) {
					return true;
				}
			}); 
			this.list.splice( index,1 );

		},
		search(keywords){ // 根据关键字，进行数据的搜索
			/*var newList = [];
			this.list.forEach( item => {
				if ( item.name.indexOf(keywords) != -1 ) {
					newList.push( item );
				}
			});
			return newList;*/

			// 注意：  forEach   some   filter   findIndex   这些都属于数组的新方法，
			// 都会对数组中的每一项，进行遍历，执行相关的操作；
			return this.list.filter( item => {
				if ( item.name.includes( keywords ) ) {
					return item;
				}
			});

		}
	}
});
</script>																			
</body>
</html>